<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="关键字" prop="keyword">
        <el-input
          v-model="queryParams.keyword"
          placeholder="请输入关键字"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="物料编码" prop="materialCode">
        <el-input
          v-model="queryParams.materialCode"
          placeholder="请输入物料编码"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['asset:material:outbound:add']"
          >新增出库</el-button
        >
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="outboundList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="序号" width="60" align="center" type="index" />
      <el-table-column label="物料名称" align="center" prop="name" :show-overflow-tooltip="true" />
      <el-table-column label="物料编码" align="center" prop="code" :show-overflow-tooltip="true" />
      <el-table-column label="物料型号" align="center" prop="model" :show-overflow-tooltip="true" />
      <el-table-column label="单位" align="center" prop="unit" :show-overflow-tooltip="true" />
      <el-table-column label="厂家" align="center" prop="factory" :show-overflow-tooltip="true" />
      <!-- <el-table-column label="当前数量" align="center" prop="currentTotal" :show-overflow-tooltip="true" /> -->
      <el-table-column label="出库数量" align="center" prop="number" :show-overflow-tooltip="true" />
      <el-table-column label="出库人" align="center" prop="createUserName" :show-overflow-tooltip="true" />
      <el-table-column label="出库理由" align="center" prop="reason" :show-overflow-tooltip="true" />
      <el-table-column
        label="出库时间"
        align="center"
        prop="createTime"
        width="180"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加物料出库对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form
        ref="outboundRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="物料" prop="materialId">
          <el-select
            v-model="form.materialId"
            placeholder="请选择物料"
            clearable
            filterable
            style="width: 100%"
            @change="handleMaterialChange"
          >
            <el-option
              v-for="item in materialOptions"
              :key="item.materialId"
              :label="item.name + ' (' + item.code + ')'"
              :value="item.materialId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="物料名称">
          <el-input v-model="selectedMaterial.name" disabled />
        </el-form-item>
        <el-form-item label="物料编码">
          <el-input v-model="selectedMaterial.code" disabled />
        </el-form-item>
        <el-form-item label="物料型号">
          <el-input v-model="selectedMaterial.model" disabled />
        </el-form-item>
        <el-form-item label="当前库存">
          <el-input v-model="selectedMaterial.currentTotal" disabled />
        </el-form-item>
        <el-form-item label="出库数量" prop="number">
          <el-input-number
            v-model="form.number"
            :min="1"
            :max="selectedMaterial.currentTotal || 1"
            :precision="0"
            style="width: 100%"
            placeholder="请输入出库数量"
          />
        </el-form-item>
        <el-form-item label="出库理由" prop="reason">
          <el-input
            v-model="form.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入出库理由"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Outbound">
import {
  listOutbound,
  addOutbound,
} from "@/api/asset/outbound";
import { listMaterial } from "@/api/asset/material";

const { proxy } = getCurrentInstance();

const outboundList = ref([]);
const open = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const materialOptions = ref([]);
const selectedMaterial = ref({
  name: '',
  code: '',
  model: '',
  currentTotal: 0
});
const submitLoading = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    keyword: undefined,
    // materialCode: undefined,
  },
  rules: {
    materialId: [{ required: true, message: "请选择物料", trigger: "change" }],
    number: [{ required: true, message: "出库数量不能为空", trigger: "blur" }],
    reason: [{ required: true, message: "出库理由不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询物料出库列表 */
function getList() {
  loading.value = true;
  listOutbound(queryParams.value).then((response) => {
    outboundList.value = response.data.rows;
    total.value = response.data.total;
    loading.value = false;
  });
}

/** 获取物料列表作为选项 */
function getMaterialOptions() {
  listMaterial({ pageSize: 100 }).then((response) => {
    materialOptions.value = response.data.rows.filter(item => item.currentTotal > 0);
  });
}

/** 物料选择变更处理 */
function handleMaterialChange(materialId) {
  if (materialId) {
    const material = materialOptions.value.find(item => item.materialId === materialId);
    if (material) {
      selectedMaterial.value = material;
      // 确保出库数量不超过当前库存
      if (form.value.number > material.currentTotal) {
        form.value.number = material.currentTotal;
      }
    }
  } else {
    selectedMaterial.value = {
      name: '',
      code: '',
      model: '',
      currentTotal: 0
    };
  }
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    outboundId: '0',
    materialId: undefined,
    number: 1,
    reason: ''
  };
  selectedMaterial.value = {
    name: '',
    code: '',
    model: '',
    currentTotal: 0
  };
  proxy.resetForm("outboundRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  Object.keys(queryParams.value).forEach((key) => {
    if (key !== "pageNum" && key !== "pageSize") {
      queryParams.value[key] = undefined;
    }
  });
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.outboundId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  getMaterialOptions();
  open.value = true;
  title.value = "添加物料出库";
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["outboundRef"].validate((valid) => {
    if (valid) {
      // 验证出库数量不超过库存
      if (form.value.number > selectedMaterial.value.currentTotal) {
        proxy.$modal.msgError("出库数量不能超过当前库存");
        return;
      }
      
      submitLoading.value = true;
      addOutbound(form.value).then((response) => {
        proxy.$modal.msgSuccess("出库成功");
        open.value = false;
        getList();
      }).catch(() => {
        
      }).finally(() => {
        submitLoading.value = false;
      });
    }
  });
}

// 页面初始化
onMounted(() => {
  getList();
});
</script> 